const { getCurrentDateTime } = require("../modal/time.config");
const STATE = {
  LOW: 0,
  UP: 1,
};

const resolveDataFun = (req, list) => {
  return new Promise((resolve, reject) => {
    let p = list.map(async (v) => {
      v.section = JSON.parse(v.section);
      const arr=v.categoryId.split(',')
      v.categoryId = arr;
      const newData = await req.services.CategoryService.findById(arr[arr.length-1]);
      v.categoryInfo = newData;
      return v;
    });
    Promise.all(p).then((res) => {
      resolve(res);
    });
  });
};

const resolveRecordDataFun = (req, list) => {
  return new Promise((resolve, reject) => {
    const p = list.map(async (item, index) => {
      item.userInfo = await req.services.UserService.findById(item.userId);
      item.username = item.userInfo.username
      return item;
    });
    Promise.all(p).then((res) => {
      resolve(res);
    });
  });
};

exports.create = async (req, res) => {
  const body = req.body;
  const {
    title,
    categoryId,
    section,
    introduce,
    state = STATE.UP,
    cover,
  } = body;
  const data = {
    title,
    categoryId: categoryId.join(","),
    cover,
    section: JSON.stringify(section),
    introduce,
    state,
    create_time: getCurrentDateTime(),
    update_time: getCurrentDateTime(),
  };
  const newData = await req.services.CourseService.create(data);
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "新增成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.list = async (req, res) => {
  const body = req.body;
  const {
    title = "",
    categoryId ='',
    section = "",
    introduce = "",
    state = "",
    page = null,
    pageSize = null,
    desc = "id",
  } = body;
  let newData = await req.services.CourseService.getList({
    where: {  state },
    like: { categoryId,title, section, introduce },
    page,
    pageSize,
    desc
  });
  let count = await req.services.CourseService.getCount({
    where: { categoryId, state },
    like: { title, introduce },
  });
  const result = await resolveDataFun(req, newData);

  res.status(200).json({
    data: { list: result, total: count },
    msg: "success",
    code: 200,
  });
};

exports.update = async (req, res) => {
  const body = req.body;
  const { title, categoryId, section, introduce, state, id, cover } = body;
  const update_time = getCurrentDateTime();
  const data = {
    title,
    categoryId: categoryId.join(","),
    section: JSON.stringify(section),
    introduce,
    state,
    update_time,
  };
  const newData = await req.services.CourseService.update(data, {
    id,
  });
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "更新成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.getDetail = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.CourseService.findById(id);
  if (newData) {
    const result = await resolveDataFun(req, [newData]);
    res.status(200).json({ data: result[0], msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};

exports.del = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.CourseService.delete(Number(id));
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "删除成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};

exports.createHistoryDetail = async (req, res) => {
  const body = req.body;
  const { courseId, sectionId, duration } = body;
  //记录观看历史
  const user = await req.services.UserService.decodeToken();
  let oldData = await req.services.CourseService.getHistoryList({
    where: { course_id: courseId, userId: user.userId },
  });
  let isAdd = true;
  if (oldData && oldData.length > 0) isAdd = false;
  const course = await req.services.CourseService.findById(courseId);
  const section = JSON.parse(course.section);
  const newSection = section.filter((v) => v.id === Number(sectionId))[0];
  if (isAdd) {
    const data = {
      course_id: courseId,
      course_cover: course.cover,
      course_title: course.title,
      section_id: sectionId,
      section_title: newSection?.title,
      section_url: newSection?.url,
      duration,
      userId: user.userId,
      create_time: getCurrentDateTime(),
      update_time: getCurrentDateTime(),
    };
    const newData = await req.services.CourseService.createHistory(data);
    if (newData.affectedRows === 1) {
      res.status(200).json({ data: "新增成功", msg: "success", code: 200 });
    } else {
      res
        .status(200)
        .json({ data: "系统错误，请重试", msg: "fail", code: 500 });
    }
  } else {
    const data = {
      course_id: courseId,
      course_cover: course.cover,
      course_title: course.title,
      section_id: sectionId,
      section_title: newSection?.title,
      section_url: newSection?.url,
      duration,
      update_time: getCurrentDateTime(),
    };
    const newData = await req.services.CourseService.updateHistory(data, {
      course_id: courseId,
      userId: user.userId,
    });
    if (newData.affectedRows === 1) {
      res.status(200).json({ data: "新增成功", msg: "success", code: 200 });
    } else {
      res
        .status(200)
        .json({ data: "系统错误，请重试", msg: "fail", code: 500 });
    }
  }
};

exports.historyList = async (req, res) => {
  const body = req.body;
  const { courseId = "", userId = "" } = body;
  let where = { course_id: courseId };
  const user = await req.services.UserService.decodeToken();
  where.userId = user.role === "user" ? user.userId : userId;
  let newData = await req.services.CourseService.getHistoryList({
    where,
  });
  const result=await resolveRecordDataFun(req,newData)

  res.status(200).json({
    data: result,
    msg: "success",
    code: 200,
  });
};

exports.getHistoryByCourseId = async (req, res) => {
  const body = req.query;
  const { courseId = "", userId = "" } = body;
  let where = { course_id: courseId };
  const user = await req.services.UserService.decodeToken();
  where.userId = user.role === "user" ? user.userId : userId;
  let newData = await req.services.CourseService.findHistoryByCourseId(where);
  res.status(200).json({
    data: newData,
    msg: "success",
    code: 200,
  });
};
